package com.mobileservice.autoreply.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;

import com.mobileservice.autoreply.R;
import com.mobileservice.autoreply.common.constant.CommConstant;
import com.mobileservice.autoreply.data.manager.PhoneContactManager;
import com.mobileservice.autoreply.ui.model.PhoneContactModel;

public class SplashScreen extends Activity {

	private static final int SPLASH_TIME = 3 * 1000;// 3 seconds
	private SharedPreferences pre;
	private boolean isFirstTime;
	private PhoneContactManager phoneContactManager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.splashscreen);

		pre = getSharedPreferences(CommConstant.PREFS, MODE_PRIVATE);
		isFirstTime = pre.getBoolean(CommConstant.FIRST_TIME_LOG, true);
		phoneContactManager = PhoneContactManager.getInstance(getApplicationContext());
		if (!isFirstTime) {
			new Handler().postDelayed(new Runnable() {

				@Override
				public void run() {

					Intent intent = new Intent(SplashScreen.this, MainActivity.class);
					startActivity(intent);

					SplashScreen.this.finish();

					overridePendingTransition(R.anim.fade_in, R.anim.fade_out);

				}
			}, SPLASH_TIME);

			new Handler().postDelayed(new Runnable() {
				@Override
				public void run() {
				}
			}, SPLASH_TIME);
		} else {
			new InsertFirstTimeLogApplication().execute();
		}
	}

	private class InsertFirstTimeLogApplication extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
			phoneContactManager.InsertorUpdatePhoneContacts(cursor);
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			Editor editor = pre.edit();
			editor.putBoolean(CommConstant.FIRST_TIME_LOG, false);
			editor.putBoolean(CommConstant.BLOCK_CALL_PREFS, true);
			editor.putBoolean(CommConstant.BLOCK_SMS_PREFS, true);
			editor.putBoolean(CommConstant.AUTO_REPLY_PREFS, true);
			editor.commit();
			Intent intent = new Intent(SplashScreen.this, MainActivity.class);
			startActivity(intent);

			SplashScreen.this.finish();

			overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
		}

	}

	@Override
	public void onBackPressed() {
		this.finish();
		super.onBackPressed();
	}
}
